package com.tcs.service;

import com.google.common.collect.Lists;
import com.tcs.annotation.MapOfKey;
import com.tcs.annotation.NettyContoller;
import com.tcs.model.datastandardization.RequestStanBean;
import com.tcs.model.datastandardization.ResponseStanBean;
import com.tcs.model.teachertest.SelectBean;
import com.tcs.model.teachertest.TopicBean;
import com.tcs.server.teacher.ITeacherService;
import com.tcs.util.uuid.UUIDUtil;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@NettyContoller
@Service(value = "dataHandleService")
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DataHandleService implements IDataHandleService {

    private final Logger logger = LoggerFactory.getLogger(DataHandleService.class);

    private List<TopicBean> topicBeanList = Lists.newArrayList();

    private Integer orderIndex = 1;                                     // 累加

    private Integer yearSubjectId = 0;                                 // 年度ID

    @Resource(name = "teacherService")
    private ITeacherService teacherService;

    @MapOfKey(key=1)
    @Override
    public ResponseStanBean handleData(ChannelHandlerContext ctx , Object msg) {
        ResponseStanBean responseStanBean = new ResponseStanBean();
        RequestStanBean requestStanBean = (RequestStanBean)msg;
        yearSubjectId = requestStanBean.getYearSubjectId();
        if (this.checkData(requestStanBean) && StringUtils.isNotBlank(requestStanBean.getMessage())) {
            yearSubjectId = requestStanBean.getYearSubjectId();
            try {
                parseRule(requestStanBean.getMessage());
            } catch (Exception e) {
                responseStanBean.setErrorCode(1);
                responseStanBean.setErrorMessage("error");
                logger.error("" , e);
            }
            responseStanBean.setMessage("success!");
        } else {
            responseStanBean.setErrorCode(1);
            responseStanBean.setErrorMessage("error");
        }
        logger.info(" requestStanBean : {} , responseStanBean : {}" , requestStanBean , responseStanBean);
        return responseStanBean;
    }

    @Override
    public Boolean checkData(RequestStanBean requestStanBean) {
        if (null != requestStanBean) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    private void parseRule(String message) {
        if (StringUtils.isNotBlank(message)) {
            String [] tempDataArray = message.split(",");
            if (ArrayUtils.isNotEmpty(tempDataArray)) {
                for (String tempStr : tempDataArray) {
                    String [] tempStrArray = tempStr.split("@");
                    conventBean(tempStrArray);
                }
            }
        }
        teacherService.saveTopicBeanList(topicBeanList);
    }

    private void conventBean(String [] dataArray) {
        if (ArrayUtils.isNotEmpty(dataArray)) {
            TopicBean topicBean = getTopicBean(dataArray);
            List<SelectBean> selectList = Lists.newArrayList();
            if (dataArray.length >= 4) {
                // 选择题 答案(答案,解析)有2行,所以要-2
                for (int i = 1; i < dataArray.length - 3; i++) {
                    SelectBean selectBean = null;
                    try {
                        selectBean = getSelectBean(dataArray[i] , i - 1);
                    } catch (Exception e) {
                        logger.error(" 发生了异常: " + Arrays.toString(dataArray) + " index : " + (i - 1) , e);
                    }
                    selectList.add(selectBean);
                }
                topicBean.setSelectList(selectList);
            }
            topicBeanList.add(topicBean);
        }
    }

    private TopicBean getTopicBean(String [] dataArray) {
        TopicBean topicBean = new TopicBean();
        try {
            topicBean.setId(UUIDUtil.getUUID());
            topicBean.setTitle(dataArray[0]);
            if (dataArray.length >= 5) {
                // TODO 数组长度为6. 5和6都为答案. 所以要 搞清楚 tiShi 有没有使用过.
                topicBean.setDaan(dataArray[5] + dataArray[6]);
                topicBean.setTopicTypeId(NumberUtils.toInt(dataArray[7]));
            } else {
                topicBean.setDaan(dataArray[1]);
                topicBean.setTopicTypeId(NumberUtils.toInt(dataArray[2]));
            }
            topicBean.setOrderIndex(orderIndex++);
            topicBean.setTiShi("null");
            topicBean.setYearSubjectId(yearSubjectId);
        } catch (Exception e) {
            logger.error(Arrays.toString(dataArray) + "\n" , e);
        }
        return topicBean;
    }

    private SelectBean getSelectBean(String selectStr , int index) {
        SelectBean selectBean = new SelectBean();
        selectBean.setId(UUIDUtil.getUUID());
        selectBean.setDaiMa(daiMaArray[index]);
        selectBean.setOrderIndex(index);
        selectBean.setTitle(selectStr);
        return selectBean;
    }

    final String [] daiMaArray = new String[]{"A","B","C","D"};

}
